import json

from com.maycur.gateway.common.base_entity import ApiTaskSet, SequentialApiTaskSet
from locust import task, tag

from com.maycur.utils import TimeUtils


class DataReimburse(SequentialApiTaskSet):
    expense_code: str
    reimburse_data: str
    task_id: str
    form_data_code: str
    reimburse_code: str

    @task
    def save_expense(self):
        timestamp = TimeUtils.current_timestamp()
        expense_url = f'{self.get_app_host()}/api/web/expense/save'
        request_body = {"adjustReason": "", "expenseTypeCode": "2002_03",
                        "consumeAmount": {"currency": "CNY", "toCurrency": "CNY", "amount": 10000},
                        "consumeTime": {"currentTime": {timestamp}},
                        "consumeLocation": {"cityPair": {"departure": "domestic-ZH5", "destination": "domestic-ZH6"}},
                        "referenceFormCode": "DFM2206092029GZCW", "customObject": {}, "expenseRegulateObject": {},
                        "amount": {"currency": "CNY", "toCurrency": "CNY", "amount": 10000}, "corpExpense": False}
        json_body = json.dumps(request_body)
        with self.client.post(expense_url, data=json_body, headers=self.get_headers_with_content_type(),
                              march_response=True) as res:
            result_dto = self.parse_response(res)
            if result_dto is None:
                self.expense_code = None
                return
            self.expense_code = result_dto.data['code']

    @task
    def save_reimburse(self):
        reimburse_url = f'{self.get_app_host()}/api/web/reimburse/save'
        request_body = {"customObject": {},
                        "coverUser": {"userCode": "UI2206092025C39C", "userName": "张玉林", "userEmployeeNo": "210433"},
                        "coverDepartment": {"code": "DI2206092025WETD", "name": "压力测试公司",
                                            "heirCode": "DI2206092025WETD", "businessCode": "DI2206092025WETD",
                                            "deptCorpFullPath": "压力测试公司"}, "referenceFormCode": "DFM220609202C4BNK",
                        "formSubTypeCode": "FT220609202D1V28",
                        "legalEntity": {"code": "ELC2206092026U7PC", "name": "压力测试公司", "baseCcy": "CNY"},
                        "reimburseAmount": {"currency": "CNY", "amount": 10000},
                        "entPayAmount": {"currency": "CNY", "amount": 0},
                        "approvedAmount": {"currency": "CNY", "amount": 10000},
                        "afterwardsPayAmount": {"currency": "CNY", "amount": 0},
                        "deductionAmount": {"amount": 0, "currency": "CNY"}, "reimburseName": "测试n",
                        "payeeAccount": {"bankCountry": "CHINA", "bankAcctNumber": "A23456",
                                         "bankBranchName": "上海银行股份有限公司大团支行", "bankName": "上海银行",
                                         "bankBranchNo": "325290004933", "bankCode": "bos",
                                         "bankLocation": "domestic-ZH4-ZH4_0", "bankAcctName": "测试账户",
                                         "bankBranchBizCode": "325290004933", "isDefault": True, "paymentType": "BANK",
                                         "accountType": "PERSONAL", "hasBankBranch": True,
                                         "userCode": "UI2206092025C39C",
                                         "acceptCcyDetail": {"code": "CNY", "name": "人民币", "symbol": "￥",
                                                             "popularity": 1, "currencyNo": 156, "fractional": 2},
                                         "abroadExpand": {"bankCode": "bos", "bankAcctNumber": "A23456",
                                                          "bankAcctName": "测试账户", "bankBranchName": "上海银行股份有限公司大团支行",
                                                          "bankName": "上海银行", "bankLocation": "domestic-ZH4-ZH4_0",
                                                          "bankCountry": "CHINA", "paymentType": "BANK",
                                                          "bankBranchBizCode": "325290004933", "countryCode": "CHINA",
                                                          "bankBranchNo": "325290004933", "account": "",
                                                          "paymentScope": ["pay_employee"],
                                                          "acceptCcyDetail": {"code": "CNY", "name": "人民币"}},
                                         "bankAcctCode": "BCD22061510Q0SG3K"}, "expenseList": [
                {"expenseTypeCode": "2002_03", "expenseTypeName": "火车", "iconCode": "train", "viceExpenseTypeCode": "",
                 "viceExpenseTypeName": "", "viceIconCode": "", "userCode": "UI2206092025C39C",
                 "optionalExpenseType": True,
                 "expenseRegulateObject": {"containBreakfast": {"code": "UNKNOWN", "name": "未知"}},
                 "invoiceGenerateExpense": False, "invoiceStatus": 0, "invoiceSubmitTime": 0,
                 "invoiceExpectSubmitTime": 0, "invoiceSource": "PHOTO_IMPORT", "corpExpense": False,
                 "autoCalculateAllowance": False, "invoiceModify": False, "originalUserCode": "UI2206092025C39C",
                 "autoCalculateBillExpense": False, "expenseInvoiceGroup": "NO_INVOICE_GROUP", "aloneDisplay": False,
                 "allocationRuleCode": "", "allocationFormCode": "", "exchangeScore": False,
                 "invoiceList": {"invoiceStatus": 0, "invoiceSubmitTime": 0, "invoiceExpectSubmitTime": 0},
                 "changeExpenseSceneFlag": False, "hotel": "", "integrity": True, "noticeMessage": [],
                 "exchangeRate": 0, "acceptToBaseExchangeRate": 1, "consumeToAcceptExchangeRate": 1,
                 "sysExchangeRate": 0, "comments": "", "approvedAmount": {"currency": "CNY", "amount": 10000},
                 "invoiceTitleConflictWithExpense": False, "originalCarAllowanceUnitPrice": 0,
                 "originalCarAllowanceAmount": {"amount": 0, "currency": "CNY", "amountStr": "￥0.00"}, "status": "OPEN",
                 "fillUserName": "张玉林", "valid": False, "code": "{self.expense_code}",
                 "approvedBaseAmount": {"amount": 0, "currency": "CNY", "amountStr": "￥0.00"}, "customExchangeRate": 0,
                 "toCurrency": "CNY", "baseAmount": {"amount": 10000, "currency": "CNY", "amountStr": "￥10,000.00"},
                 "platformCode": "", "adjustReason": "", "customObject": {},
                 "amount": {"currency": "CNY", "amount": 10000}, "sourceType": "", "editByOwner": False,
                 "consumeAmount": {"amount": 10000, "currency": "CNY", "customExchangeRate": 0, "toCurrency": "CNY",
                                   "amountStr": "￥10,000.00"}, "lackRequiredInfo": False,
                 "nuTaxAmount": {"amount": 10000, "currency": "CNY", "amountStr": "￥10,000.00"},
                 "invoiceValidateStatus": "NOT_VALIDATION", "deductionFlag": False,
                 "acceptAmount": {"amount": 10000, "currency": "CNY", "amountStr": "￥10,000.00"},
                 "approvedAcceptAmount": {"amount": 10000, "currency": "CNY", "amountStr": "￥10,000.00"},
                 "approvedConsumeAmount": {"amount": 10000, "currency": "CNY", "amountStr": "￥10,000.00"},
                 "extraTag": [], "deductionAmount": {"amount": 0, "currency": "CNY", "amountStr": "￥0.00"},
                 "reimburseStatus": "未报销", "allocated": False, "delegation": False,
                 "consumeTime": {"currentTime": 1655263267543},
                 "consumeLocation": {"cityPair": {"departure": "domestic-ZH5", "destination": "domestic-ZH6"}},
                 "payAfterwards": False, "sourceId": "", "businessPurpose": "", "expenseTypeGroupTag": "",
                 "taxRateCategory": "", "taxCode": "", "splitSourceCode": "", "liteDataCode": "",
                 "splitTag": "NOT_SPLIT", "taxRate": 0,
                 "taxAmount": {"amount": 0, "currency": "CNY", "amountStr": "￥0.00"},
                 "subsidiaryCode": "SI2206092025WETC", "taxRateCode": "", "createTime": 1655263287717,
                 "invoiceCount": 0, "reimburseDataCode": "", "referenceFormCode": "DFM2206092029GZCW",
                 "freeInvoice": False, "updatedTime": 0, "expenseCcyCode": "CNY", "createManually": False,
                 "autoCreatedEditByAuthor": False, "notSubjectApplicationQuotaLimit": False, "consumeCcyCode": "CNY",
                 "changeCarAllowance": False}], "loanDeductionList": [], "personBankAcctCode": "BCD22061510Q0SG3K",
                        "submitFlag": True, "payableAmount": {"currency": "CNY", "amount": 10000}}
        json_body = json.dumps(request_body)
        with self.client.post(reimburse_url, data=json_body, headers=self.get_headers_with_content_type(),
                              march_response=True) as res:
            result_dto = self.parse_response(res)
            if result_dto is None:
                return
            self.reimburse_data = result_dto.data

    @task
    def submit_reimbures(self):
        submit_reimburse_url = f'{self.get_app_host()}/api/web/reimburse/submit/{self.reimburse_data}'
        request_body = {"tasks": [], "externalTasks": [], "formHasTravelPartnerField": False,
                        "expenseHasTravelPartnerField": {f'{self.expense_code}': False},
                        "routeHasTravelPartnerField": False}
        json_body = json.dumps(request_body)
        with self.client.post(request_body, data=json_body, headers=self.get_headers_with_content_type(),
                              march_repsonse=True) as res:
            resource_dto = self.parse_response(res)
            if resource_dto is None:
                return
            self.form_data_code = resource_dto.data['payeeAccount']['reimburseDataCode']
            self.reimburse_code = resource_dto.data['reimburseCode']

    # select
    # task.id_ as id
    # from act_ru_task  task
    # left
    # join
    # reimburse_data
    # data
    # on
    # task.proc_inst_id_ = data.proc_inst_id
    # where
    # data.enterprise_code = '${entCode}' and data.reimburse_code = '${reimburseCode}';

    @task
    def approval_agree(self):
        timestamp = TimeUtils.current_timestamp()
        approval_agree_url = f'{self.get_app_host()}api/web/reimburse/approval/agree'
        request_body = {
            "procTaskId": f'{self.task_id}',
            "reimburseDataCode": f'{self.form_data_code}',
            "reason": "同意",
            "remindedUserCodes": [

            ],
            "validationResult": {
                "details": [

                ],
                "validatedAt": f'{timestamp}'
            }
        }
        json_body = json.dumps(request_body)
        with self.client.post(approval_agree_url, data=json_body, headers=self.get_headers_with_content_type(),
                              catch_response=True) as res:
            self.parse_response(res)
